#include<iostream>
#include<sys/shm.h>
#include<unistd.h>
#include<string.h>
#include<sys/wait.h>

using namespace std;

int main()
{
    key_t key=ftok("corres.txt",0);
    int id=shmget(key,4096,0664|IPC_CREAT);
    if(id<0)
    {
        perror("shmget");
        exit(-1);
    }

    pid_t pid1 =fork();
    pid_t pid2=-1;
    if(pid1>0)
    {
        pid2 =fork();
        if(pid1<0||pid2<0)
        {
            perror("fork()");
            exit(-1);
        }
    }

    if(0==pid1)
    {
        char* buf=reinterpret_cast<char*>(shmat(id,NULL,0));
        strcpy(buf,"i am process A\n");
        shmdt(buf);
        return 0;
    }
    if(0==pid2)
    {
        char* buf=reinterpret_cast<char*>(shmat(id,NULL,0));
        cout<<buf;
        shmdt(buf);
        return 0;
    }
    waitpid(pid1,NULL,0);
    waitpid(pid2,NULL,0);
    shmctl(id,IPC_RMID,NULL);

    return 0;
}